package com.hsnn.medstgmini.base.std.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicSys;
import com.hsnn.medstgmini.base.dict.model.form.DicAreaForm;
import com.hsnn.medstgmini.base.dict.service.DicAreaManager;
import com.hsnn.medstgmini.base.dict.service.DicHosptypeManager;
import com.hsnn.medstgmini.base.std.model.HospInfo;
import com.hsnn.medstgmini.base.std.model.HospInfoLog;
import com.hsnn.medstgmini.base.std.model.HospLevel;
import com.hsnn.medstgmini.base.std.service.StdHospInfoManager;
import com.hsnn.medstgmini.exception.MSException;
import com.hsnn.medstgmini.pro.project.service.BidProjproddrugManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.AccountUtil;
import com.hsnn.medstgmini.util.AreaUtil;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.DicSysUtil;
import com.hsnn.medstgmini.util.ExcelUtil;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 医疗机构库
 * @author CCL
 */
@Controller
@RequestMapping("stdHospInfo")
public class StdHospInfoController {
	
	private static final Logger log = Logger.getLogger(StdHospInfoController.class);

	@Autowired
	private StdHospInfoManager hospInfoManager;

	@Autowired
	private DicHosptypeManager hosptypeManager;

	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private BidProjproddrugManager bidProjproddrugManager;
	
	@Value("#{sysProp['system.province']}")
    private String sysProvince;
	
	@Autowired
	private DicAreaManager dicAreaManager;
	
	/**
	 * @category 获取user信息
	 * @param 
	 * @return  SysUser
	 */
	public SysUser getUser(){
		return (SysUser) request.getSession().getAttribute(Constants.USERINFO);
	}
	/**
	 * @category 医疗机构列表页面
	 * @param model
	 * @return
	 */
	@RequestMapping("hospInfoList")
	public String hospInfoList(Model model) {
		 printParams();
		try {
			DicAreaForm dicArea = dicAreaManager.getDicAreaById(sysProvince);
			request.setAttribute("sysProvinceName", dicArea.getAreaName());
			request.setAttribute("sysProvince", sysProvince);
		} catch (Exception e) {
			log.error("查询出错", e);
		}
		return "/base/std/hospInfoList";
	}

	/**
	 * @category 查询医疗机构列表
	 * @param hospInfo
	 * @return
	 */
	@RequestMapping("getHospInfoList")
	@ResponseBody
	public Pagination getHospInfoList(HospInfo hospInfo) {
		printParams();
		Pagination page = new Pagination(request);
		String hospClassifys = request.getParameter("hospClassifys");
		page.getConditions().put("hospClassifys", hospClassifys);
		String hospType = request.getParameter("hospType");
		page.getConditions().put("hospType", hospType);
		try{
			page = hospInfoManager.getHospInfoPage(page, hospInfo);
			page.setSuccess(true);
		} catch(Exception e) {
			page.setSuccess(false);
			log.error("查询出错", e);
		}
		return page;
	}
	
	
	/**
	 * @category 医疗机构维护记录页面
	 * @param model
	 * @param hospId
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("hospInfoLogList")
	public String hospLogList(Model model, String hospId) throws UnsupportedEncodingException {
		 printParams();
		model.addAttribute("hospId", hospId);
		String hospName = new String(request.getParameter("hospName").getBytes("ISO8859-1"),"utf-8");
		model.addAttribute("hospName",hospName);
		String hospCode = new String(request.getParameter("hospCode"));
		model.addAttribute("hospCode", hospCode);
		return "/base/std/hospInfoLogList";
	}

	/**
	 * @category 查询医疗机构维护记录
	 * @param model
	 * @param hospId
	 * @return
	 */
	@RequestMapping("getHospInfoLogList")
	@ResponseBody
	public Pagination getHospInfoLogList(HospInfoLog hospInfoLog) {
		 printParams();
		Pagination page = new Pagination(request);
		String startTime = (String) request.getParameter("startPoint");
		String endTime = (String) request.getParameter("endPoint");
		if(null != startTime && !"".equals(startTime)){
			hospInfoLog.setStartTime(DateUtil.parseDateTime(startTime));
		}
		if(null != endTime && !"".equals("endTime")){
			hospInfoLog.setEndTime(DateUtil.parseDateTime(endTime));
		}
		try {
			page = hospInfoManager.getHospInfoLogPage(page, hospInfoLog);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 跳转新增编辑页面
	 * @param model
	 * @param opType
	 * @param hospId
	 * @return
	 */
	@RequestMapping(value={"/add","/edit"})
	public String editHospInfo(Model model, int opType, String hospId) {
		 printParams();
		HospInfo hospInfo = new HospInfo();
		if (opType == Constants.OP_TYPE_EDIT) {
			if (hospId != null && !"".equals(hospId)) {
				hospInfo = hospInfoManager.getHospInfoById(hospId);
				hospInfo = hospInfo == null ? new HospInfo() : hospInfo;
			}
		}
		List<DicSys> dicSysList = DicSysUtil.getDicListByClassCode(Constants.HOSP_CAT);
		for(int i = 0; i < dicSysList.size(); i++){
			DicSys dicSys = dicSysList.get(i);
			if(dicSys.getStatus() == 0){
				dicSysList.remove(i);
			}
		}
		model.addAttribute("opType", opType);
		model.addAttribute("classifyList", dicSysList);
		model.addAttribute("levelList", HospLevel.values());
		model.addAttribute("hospInfo", hospInfo);
		model.addAttribute("areaId", sysProvince);
		return "/base/std/editHospInfo";
	}

	
	
	/**
	 * @category 保存医疗机构信息
	 * @param hospInfo
	 * @param opType
	 * @return
	 */
	@RequestMapping("saveHospInfo")
	@ResponseBody
	public Pagination saveHospInfo(HospInfo hospInfo, int opType) {
		 printParams();
		Pagination page = new Pagination();
		try {
			if (hospInfo != null) {
				
				if(StringUtils.isBlank(hospInfo.getHospCode())){
					hospInfo.setHospCode(AccountUtil.getStdSequence(Constants.STD_YILIAOJIGOU_PREFIX, Constants.STD_YILIAOJIGOU, Constants.STD_YILIAOJIGOU_LEN));
					page.setMsg(hospInfo.getHospCode());
				}
				hospInfo.setUpdUser(getUser().getId());
				hospInfoManager.saveHospInfo(hospInfo, opType);			
				page.setSuccess(true);
			}
			
		} catch (MSException e) {
			log.error("",e);
			page.setSuccess(false);
			page.setMsg(e.getMsg());
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
			page.setMsg("保存失败！");
		}
		return page;
	}


	/**
	 * @category 批量(启用|停用)
	 * @param array
	 * @return
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination batchChangeStatus(HospInfo hospId) {
		 printParams();
		String array = request.getParameter("array");
		String status = request.getParameter("status");
		Pagination page = new Pagination();
		try {
			if (StringUtils.isNotBlank(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<String>>() {
				}.getType();
				List<String> list = gson.fromJson(array, type);
				if (list != null && !list.isEmpty()) {
					page.setForm(list);
					page.getConditions().put("status", status);
					page.getConditions().put("updUser", getUser().getId());
					hospInfoManager.batchChangeStatus(page);
					page.setSuccess(true);
				}
			}
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 医疗机构详情
	 * @param model
	 * @param hospId
	 * @return
	 */
	@RequestMapping("hospInfoDetail")
	public String hospInfoDetail(Model model, String hospCode) {
		 printParams();
		HospInfo hospInfo = new HospInfo();
		if (StringUtils.isNotBlank(hospCode)) {
			 hospInfo = (HospInfo) bidProjproddrugManager.getUniquerResult(HospInfo.class, "hospCode", hospCode);
			hospInfo = hospInfo == null ? new HospInfo() : hospInfo;
		}
		model.addAttribute("hospInfo", hospInfo);
		return "/base/std/hospInfoDetail";
	}

	@RequestMapping("hospInfoDetailPop")
	public String hospInfoDetailPop(Model model, String hospId) {
		HospInfo hospInfo = new HospInfo();
		if (StringUtils.isNotBlank(hospId)) {
			hospInfo = hospInfoManager.getHospInfoById(hospId);
			hospInfo = hospInfo == null ? new HospInfo() : hospInfo;
		}
		model.addAttribute("hospInfo", hospInfo);
		return "/base/std/hospInfoDetailPop";
	}
	/**
	 * @category 医疗机构维护记录详情
	 * @param model
	 * @param hospInfoLog
	 * @return
	 */
	@RequestMapping("hospInfoLogDetail")
	public String hospInfoLogDetail(Model model, HospInfoLog hospInfoLog) {
		 printParams();
		List<Map<String,Object>> list = hospInfoManager.getHospCompareList(hospInfoLog);
		
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		String[] cColunm = {"医疗机构编码","医疗机构名称","医疗机构名称拼音码","医疗机构简称","医疗机构简称拼音码","注册地行政区划代码","组织机构代码","医疗机构属性","医疗机构类别","医疗机构等级","医疗机构地址","机构电话","历史医疗机构编码","合并处理状态","状态","床位数","年门诊量","员工数","注册资本","简介","法人姓名","法人身份证号","法人电话","法人手机","联系人姓名","联系人身份证号","联系人职务","联系人电话","联系人手机","联系人邮箱","联系人QQ","医疗机构执业许可证号","执业许可证号有效期始","执业许可证号有效期止","事业单位法人证书号","事业单位法人证书有效期始","事业单位法人证书有效期止"};
		String[] eColunm = {"hospCode","hospName","hospSpelCode","hospShortName","hospShortSpelCode","areaId","orgCode","hospClassifyName","hospType","hospLevelName","hospAddress","hospPhone","historyCode","mergeState","status","bedNum","incomPatNum","staffNum","regCap","profile","legalRepName","legalRepIdnum","legalRepTelephone","legalRepHandphone","contactName","contactIdnum","contactPos","contactTelephone","contactHandphone","contactEmail","contactQq","hospLiceNo","hospLiceStartDate","hospLiceEndDate","enterLiceNo","enterLiceStartDate","enterLiceEndDate"};
		for(int i = 0;i<cColunm.length;i++){
			Map<String,Object> map =  new HashMap<String,Object>();
			map.put("colunm", cColunm[i]);//字段名
			map.put("after", !"status".equals(eColunm[i])?list.get(0).get(eColunm[i]):"1".equals(list.get(0).get(eColunm[i]).toString())?"启用":"停用");//修改后数据
			map.put("before", list.size()==1?null:!"status".equals(eColunm[i])?list.get(1).get(eColunm[i]):"1".equals(list.get(1).get(eColunm[i]).toString())?"启用":"停用");//修改前数据
			if(list.size()==1){
				map.put("red", "1");//是否变红加粗 1是 0 否
			}else{
				//判断修改后与修改前数据是否相等
				if(list.get(0).get(eColunm[i])!=null&&list.get(1).get(eColunm[i])!=null&&!list.get(0).get(eColunm[i]).toString().equals(list.get(1).get(eColunm[i]).toString())){
					map.put("red", "1");
				}else{
					map.put("red", "0");
				}
			}
			mapList.add(map);
		}
		for(int i = 0;i<mapList.size();i++){//把要变红的放在list前面
			if("1".equals(mapList.get(i).get("red"))){
				dataList.add(mapList.get(i));
			}
		}
		for(int i = 0;i<mapList.size();i++){
			if("0".equals(mapList.get(i).get("red"))){
				dataList.add(mapList.get(i));
			}
		}
		request.setAttribute("dataList", dataList);
		request.setAttribute("list", list);
		/*try {
			if (hospInfoLog != null) {
				List<Map<String,String>> list = hospInfoManager.getHospCompareList(hospInfoLog);
				model.addAttribute("hospInfoLog", hospInfoLog);
				model.addAttribute("list", list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		return "/base/std/hospInfoLogDetail";
	}
	
	/**
	 * @category 判断医疗机构代码重复性
	 * @param model
	 * @param hospInfoLog
	 * @return
	 */
	@RequestMapping("testRepByHospCode")
	@ResponseBody
	public Boolean testRepByHospCode(){
		 printParams();
		String hospCode = request.getParameter("hospCode");
		String hospId = request.getParameter("hospId");
		if(null!=hospCode && !"".equals(hospCode)){
			List<HospInfo> list = hospInfoManager.getHospInfoListByHospCode(hospCode,hospId);
			if(list.size() > 0){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * @category 判断医疗机构名称重复性
	 * @param model
	 * @param hospInfoLog
	 * @return
	 */
	@RequestMapping("testRepByHospName")
	@ResponseBody
	public Boolean testRepByHospName(){
		 printParams();
		String hospName = request.getParameter("hospName");
		String hospId = request.getParameter("hospId");
		if(null!=hospName && !"".equals(hospName)){
			List<HospInfo> list = hospInfoManager.getHospInfoListByHospName(hospName,hospId);
			if(list.size() > 0){
				return true;
			}
		}
		return false;
	}
	
	
	/**
	 * 
	 *@category 获取参数打印
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
	/**
	 * 
	 *@category 导出excel
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response,String fileName){
		printParams();
		Pagination page = new Pagination();
		String hospCode = request.getParameter("hospCode");
		String hospName = request.getParameter("hospName");
		String hospClassify = request.getParameter("hospClassify");
		String area1 = request.getParameter("area1");
		String area2 = request.getParameter("area2");
		String area3 = request.getParameter("area3");
		String areaId = AreaUtil.getAreaStartCode(area1, area2, area3);
		
		if (StringUtils.isBlank(areaId)) {
		    areaId = sysProvince.substring(0, 2);
		}
		
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(hospCode)){
			page.getConditions().put("hospCode", hospCode.trim());
		}
		if(StringUtils.isNotBlank(hospName)){
			page.getConditions().put("hospName", hospName.trim());
		}
		if(StringUtils.isNotBlank(hospClassify)){
			page.getConditions().put("hospClassify", hospClassify.trim());
		}
		if(StringUtils.isNotBlank(areaId)){
			page.getConditions().put("areaId", areaId.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			hospInfoManager.getStdHospinfoNoPage(page);
			String title = "医疗机构";
			String[] headers = {"医疗机构编码","医疗机构名称","医疗机构名称拼音码","医疗机构简称","医疗机构简称拼音码","注册地行政区划代码","组织机构代码","医疗机构分类","医疗机构类型","医疗机构等级","医疗机构地址","机构电话","历史医疗机构编码","合并处理状态","状态","床位数","年门诊量","员工数","注册资本","简介","法人姓名","法人身份证号","法人电话","法人手机","联系人姓名","联系人身份证号","联系人职务","联系人电话","联系人手机","联系人邮箱","联系人QQ","医疗机构执业许可证号","执业许可证号有效期始","执业许可证号有效期止","事业单位法人证书号","事业单位法人证书有效期始","事业单位法人证书有效期止"};
			String[] alias = {"hospCode","hospName","hospSpelCode","hospShortName","hospShortSpelCode","areaId","orgCode","hospClassify","hospTypeId","hospLevelId","hospAddress","hospPhone","historyCode","mergeState","status","bedNum","incomPatNum","staffNum","regCap","profile","legalRepName","legalRepIdnum","legalRepTelephone","legalRepHandphone","contactName","contactIdnum","contactPos","contactTelephone","contactHandphone","contactEmail","contactQq","hospLiceNo","hospLiceStartDate","hospLiceEndDate","enterLiceNo","enterLiceStartDate","enterLiceEndDate"};
			ExcelUtil.exportExcel(page, os, title, headers, alias);
			page.setSuccess(true);
			 
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
	
	/**
	 * @category 医疗机构详情
	 * @param model
	 * @param hospId
	 * @return
	 */
	@RequestMapping("toHospInfoByCode")
	public String toHospInfoByCode(Model model, String hospCode) {
		 printParams();
		HospInfo hospInfo = new HospInfo();
		if (StringUtils.isNotBlank(hospCode)) {
			hospInfo = hospInfoManager.getHospInfoByCode(hospCode);
			hospInfo = hospInfo == null ? new HospInfo() : hospInfo;
		}
		model.addAttribute("hospInfo", hospInfo);
		return "/base/std/hospInfoDetail";
	}
	
}
